package com.study.GameService.NetConnection;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Handler;
import android.os.Message;

public class ClientThread extends Thread {
	public Handler mListenerHandler; // Handler will receive message from thread
	String mServerAddr;
	
	//Socket client;
	private PrintWriter print = null;
	private BufferedReader reader = null;
	private Thread mWorker;
	private Socket mClient = null;
	
	public void run(){
		int ret = 1;
		try {
			mClient = new Socket(mServerAddr, ServerThread.DEFAULT_PORT);
			print = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mClient.getOutputStream())), true);
			reader = new BufferedReader(new InputStreamReader(mClient.getInputStream()));
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			CloseConnection();
			ret = 0;
		}
		if(ret == 1){
			mWorker = new Thread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					if(reader != null){
						try {
							while(true){
								String message = null;
								while((message = reader.readLine()) != null){
									Message msg = Message.obtain();
									msg.obj = message;
									//mListenerHandler.sendMessage(msg);
									GameService.SendDataBack(msg);
								}
							}
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
				}
			});
			mWorker.start();
			// Notify to Main activity
			Message msg = Message.obtain();
			msg.arg1 = ret;
			mListenerHandler.sendMessage(msg);
		}
	}
	
	public ClientThread(Handler mainHandle, String serverAddr){
		mListenerHandler = mainHandle;
		mServerAddr = serverAddr;
	}
	
	public void handleMessage(Message msg){
		String message = (String)msg.obj;
		if(print != null){
			print.println(message);
			print.flush();
		}
	}
	
	public void CloseConnection(){
		// TODO: Close client socket and in, out stream
		try {
			print.println("INFO:Quit");
			mClient.close();
			reader.close();
			print.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
